<template>
    <div>
        <van-nav-bar title="Pinia使用" fixed placeholder left-arrow @click-left="onClickLeft" />
        <div style="margin-bottom:10px;">
            <van-button type="primary" size="mini" @click="changeListForPatch">Patch修改List</van-button>
        </div>
        <div style="margin-bottom:10px;">
            <van-button type="primary" size="mini" @click="changeListAction">Action修改List</van-button>
        </div>
        <div style="margin-bottom:10px;">
            <!-- 因为开启了持久化储存 所以需要清空内容 -->
            <van-button type="primary" size="mini" @click="clearList">清空List</van-button>
        </div>
        <van-list>
            <van-cell v-for="item in list" :key="item.id" :title="item.name" />
        </van-list>
    </div>
</template>

<script setup lang="ts">
import { toRefs } from 'vue';
const onClickLeft = () => history.back();
// pinia一些优点
// 1. 舍弃了冗长的 mutations 属性
// 2. 舍弃了模块化 modules 让状态管理更加扁平化
// 3. 对于 ts 的支持更加友好 支持数据推断
// 4. 可以让各个状态管理相互依赖、嵌套
// 1 引入
import { useCounterStore } from "../stores/cart";
// 2 拿到实例
const counterStore = useCounterStore();
// 3 解构里面的变量和方法 toRefs作用是让解构出来的变量具有响应性 
const { list,addProduct,clearProduct } = toRefs(counterStore);

const changeListForPatch = () => {
    counterStore.$patch((state) => {
        state.list.push({
            id: state.list.length,
            name: 'name' + state.list.length,
            url: '111',
            price: 12,
            state: true,
            num: 1,
        })
    })
}
const changeListAction = () => {
    //变成响应式了所以需要加value
    addProduct.value({
        id: list.value.length,
        name: 'name' + list.value.length,
        url: '111',
        price: 12,
        state: true,
        num: 1,
    })
}
const clearList=()=>{
    clearProduct.value()
}
</script>

<style scoped lang="scss"></style>